---
title: "Module System and Build Tools"
description: "Learn Rust's module system, package management, and project structure, comparing them with JavaScript's modular development."
---

# Module System and Build Tools

## 📖 Learning Objectives

Understand Rust's module system and its package manager, Cargo. Learn how to organize a Rust project structure and understand the differences from JavaScript's module system.

---

## 🎯 Module System Comparison

### JavaScript's Module System

JavaScript uses the ES6 module syntax:

<UniversalEditor title="JavaScript Module System" compare={true}>
```javascript !! js
// math.js - Exporting a module
export const PI = 3.14159;

export function add(a, b) {
    return a + b;
}

export function multiply(a, b) {
    return a * b;
}

// Default export
export default class Calculator {
    constructor() {
        this.result = 0;
    }
    
    add(x) {
        this.result += x;
        return this;
    }
    
    getResult() {
        return this.result;
    }
}

// utils.js - Another module
export function formatNumber(num) {
    return num.toFixed(2);
}

// main.js - Importing a module
import Calculator, { add, multiply, PI } from './math.js';
import { formatNumber } from './utils.js';

console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8

const calc = new Calculator();
calc.add(10).add(5);
console.log(calc.getResult()); // 15

console.log(formatNumber(3.14159)); // "3.14"
```
</UniversalEditor>

### Rust's Module System

Rust uses the `mod` and `use` keywords to manage modules:

<UniversalEditor title="Rust Module System" compare={true}>
```rust !! rs
// lib.rs - The main module file
mod math; // Declare the math module
mod utils; // Declare the utils module

// Re-export module contents
pub use math::{add, multiply, PI, Calculator};
pub use utils::format_number;

// math.rs - The math module
pub const PI: f64 = 3.14159;

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

// A struct (similar to a JavaScript class)
pub struct Calculator {
    result: i32,
}

impl Calculator {
    // Constructor
    pub fn new() -> Self {
        Calculator { result: 0 }
    }
    
    pub fn add(&mut self, x: i32) -> &mut Self {
        self.result += x;
        self
    }
    
    pub fn get_result(&self) -> i32 {
        self.result
    }
}

// utils.rs - The utils module
pub fn format_number(num: f64) -> String {
    format!("{:.2}", num)
}

// main.rs - The main program
// Assuming `langshift-project` is the name of the crate (project)
use langshift_project::math::{add, multiply, PI, Calculator};
use langshift_project::utils::format_number;

fn main() {
    println!("PI = {}", PI); // PI = 3.14159
    println!("add(5, 3) = {}", add(5, 3)); // add(5, 3) = 8
    println!("multiply(4, 2) = {}", multiply(4, 2)); // multiply(4, 2) = 8
    
    let mut calc = Calculator::new();
    calc.add(10).add(5);
    println!("calc result = {}", calc.get_result()); // calc result = 15
    
    println!("formatted: {}", format_number(3.14159)); // formatted: 3.14
}
```
</UniversalEditor>

### Module System Differences

1.  **File Organization**: Rust uses `mod` to declare modules, while JavaScript uses file paths.
2.  **Visibility**: Rust requires explicit `pub` declarations to make functions and structs public.
3.  **Import Syntax**: Rust uses the `use` keyword, while JavaScript uses `import`.
4.  **Default Exports**: Rust does not have a concept of default exports; everything must be imported explicitly.

---

## 📦 Package Management System Comparison

### JavaScript's npm

<UniversalEditor title="JavaScript Package Management" compare={true}>
```json !! json
// package.json
{
  "name": "langshift-project",
  "version": "1.0.0",
  "description": "A project for learning Rust from JavaScript",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest",
    "build": "webpack"
  },
  "dependencies": {
    "lodash": "^4.17.21",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "jest": "^29.5.0",
    "webpack": "^5.88.0"
  }
}
```
```bash
# Installing dependencies
npm install lodash express
npm install --save-dev jest webpack
```
```javascript
// Using dependencies
import _ from 'lodash';
import express from 'express';

const app = express();
const numbers = [1, 2, 3, 4, 5];
const sum = _.sum(numbers);

console.log(sum); // 15
```
</UniversalEditor>

### Rust's Cargo

<UniversalEditor title="Rust Package Management" compare={true}>
```toml !! toml
// Cargo.toml - Project configuration file
[package]
name = "langshift-project"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <your.email@example.com>"]
description = "A project for learning Rust from JavaScript"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }

[dev-dependencies]
tokio-test = "0.4"
```
```bash
# Add dependencies
cargo add serde tokio reqwest
cargo add --dev tokio-test
```
```rust
// main.rs - Using dependencies
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    age: u32,
}

#[tokio::main]
async fn main() {
    let user = User {
        name: String::from("Rust"),
        age: 25,
    };
    
    // Serialize to JSON
    let json = serde_json::to_string(&user).unwrap();
    println!("JSON: {}", json);
    
    // Asynchronous task
    tokio::spawn(async {
        println!("Executing an async task...");
    });
}
```
</UniversalEditor>

### Package Management Differences

1.  **Configuration File**: npm uses `package.json`, while Cargo uses `Cargo.toml`.
2.  **Dependency Management**: Cargo's dependency management is stricter and handles version conflicts better.
3.  **Build Tool**: Cargo integrates build, test, documentation generation, and other functions.
4.  **Feature System**: Rust supports conditional compilation and feature flags. 